package com.ben.multiple.elasticsearch.template;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.search.CompletionSuggester;
import co.elastic.clients.elasticsearch.core.search.FieldSuggester;
import co.elastic.clients.elasticsearch.core.search.Suggester;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchClients;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.client.elc.NativeQuery;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.suggest.response.Suggest;

import java.util.HashMap;
import java.util.List;

public class JavaSearch3Test {
    static ElasticsearchTemplate template;
    static ElasticsearchClient client;
    static String IndexName = "phone2";
    static IndexCoordinates indexCoordinates = IndexCoordinates.of(IndexName);

    static {
        client = ElasticsearchClients.createImperative(ClientConfiguration.create("192.168.229.141:9200"));
        template = new ElasticsearchTemplate(client);
    }

    public static void main(String[] args) {
        try {
            suggest();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("=========================================");
        client.shutdown();
        System.exit(5);
    }

    private static void suggest() {

        CompletionSuggester completionSuggester = new CompletionSuggester.Builder().field("title").skipDuplicates(true).size(3).build();

        FieldSuggester fieldSuggester = new FieldSuggester.Builder().text("y").completion(completionSuggester).build();

        Suggester suggester = new Suggester.Builder().suggesters("title_suggest", fieldSuggester).build();

        NativeQuery nativeQuery = NativeQuery.builder().withSuggester(suggester).build();

        SearchHits<HashMap> hits = template.search(nativeQuery, HashMap.class, indexCoordinates);

        Suggest suggest = hits.getSuggest();
        Suggest.Suggestion<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>> titleSuggest =
                suggest.getSuggestion("title_suggest");
        List<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>> entries = titleSuggest.getEntries();
        for (Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option> entry : entries) {
            String text = entry.getText();
            System.out.println(text);
            List<? extends Suggest.Suggestion.Entry.Option> options = entry.getOptions();
            for (Suggest.Suggestion.Entry.Option option : options) {
                String v = option.getText();
                System.out.println(v);
            }
        }
    }

}
